package com.project.yunshitong;

import static com.project.yunshitong.Utils.getToast;

import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.seuic.scankey.IKeyEventCallback;
import com.seuic.scankey.ScanKeyService;
import com.seuic.scanner.DecodeInfo;
import com.seuic.scanner.DecodeInfoCallBack;
import com.seuic.scanner.Scanner;
import com.seuic.scanner.ScannerFactory;


public class ScanActivity extends AppCompatActivity implements DecodeInfoCallBack, View.OnClickListener {

    Scanner scanner;
    private ScanKeyService mScanKeyService;
    private IKeyEventCallback mCallback;
    private ImageView ivBack;
    private TextView tvCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        initView();
        initKeyEventCallback();
    }


    public void initKeyEventCallback() {
        mScanKeyService = ScanKeyService.getInstance();
        mCallback = new IKeyEventCallback.Stub() {
            @Override
            public void onKeyDown(int i) throws RemoteException {
//                Num++;
                if (i == 249 && scanner != null) {
                    scanner.startScan();
                }
//                Log.e(TAG, "onKeyDown: num==========" + Num);
//                if (i == 250 && init) {
////                    Log.e(TAG, "onKeyDown: RfidGetPower===="+RfidGetPower() );
//                    ReadRFIDOne();
//                }
            }

            @Override
            public void onKeyUp(int i) throws RemoteException {
//                Num = 0;
//        Log.v("扫描摁键抬起", "" + i);
//        Log.v("抬起次数", "" + Num);
                if (i == 249 && scanner != null) {
                    scanner.stopScan();
                }
//                if (i == 250 && init) {
//                    StopRFID();
//                }
            }
        };
//            InitScanCallBack();
        Log.v("扫描器监听摁键对象", "" + mCallback);
        if (mScanKeyService != null) {
            mScanKeyService.registerCallback(mCallback, "249,250");
        }
        scanner = ScannerFactory.getScanner(this);
        scanner.open();
        scanner.setDecodeInfoCallBack(this);
    }

    @Override
    public void onDecodeComplete(DecodeInfo decodeInfo) {
        getToast(this, "读取成功！");
        tvCode.setText(decodeInfo.barcode);
    }

    private void initView() {
        ivBack = findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this);
        tvCode = findViewById(R.id.tvCode);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
        }
    }
}